import styles from './index.module.scss'
import Button from '@c/button'
import message from '@c/message'
import cm from 'classnames'
import { userInfo } from '@/store'
import { useRecoilValue } from 'recoil'
import { useEffect, useState, useRef } from 'react'
import { payCenter, getPayResult, payDirect, clearOrderCache } from '@/api/vip'
import WechatPay from './wechat-pay'
import { goBack, openNewTab } from '@/utils/utils'
import { hashMD5 } from '@/utils/cryptojs'
import { useShowLogin } from '@/utils/hooks'
import FetchLoading from '../../fetch-loading'
import dayjs from 'dayjs'
import { paySuccessReport } from '@/utils/report'
const reportData = (data, user) => {
  const { email, expireTime } = user
  const lastTime = dayjs(expireTime * 1000).diff(new Date())
  let value = data.price
  try {
    value = data.price / 100
  } catch (error) {}
  paySuccessReport({
    user_is_vip: lastTime > 0 ? 'true' : 'false',
    pay_success_time: new Date().toLocaleString(),
    email,
    pay_price: `支付${data.price}分`,
    value,
    currency: 'RMB'
  })
}
const payArr = [
  {
    value: 1,
    icon: '/images/wechat-1.png',
    name: '微信'
  },
  {
    value: 2,
    icon: '/images/alipay-1.png',
    name: '支付宝'
  },
  {
    value: 3,
    icon: '/images/paypal-1.png',
    name: 'paypal'
  },
  {
    value: 5,
    icon: '/images/touchNGo-1.png',
    name: 'touchNGo'
  },
  {
    value: 4,
    icon: '/images/boost-1.png',
    name: 'Boost'
  },
  {
    value: 6,
    icon: '/images/grabPay-1.png',
    name: 'GrabPay'
  }
]
const quanyiArr = [
  {
    icon: '/images/v-line.webp',
    title: '最优线路'
  },
  {
    icon: '/images/v-live.webp',
    title: '电视直播'
  },
  {
    icon: '/images/v-source.webp',
    title: '资源下载'
  },
  {
    icon: '/images/v-rate.webp',
    title: '倍速播放'
  }
]
const Index = props => {
  const user = useRecoilValue(userInfo)
  const showLogin = useShowLogin()
  const { vipData, onClose, currKey = 1, h5PaySuccess } = props
  const [selected, setSelected] = useState(currKey)
  const [showWechat, setShowWechat] = useState(false)
  const [payWay, setPayWay] = useState(1)
  const [url, setUrl] = useState('')
  const [orderId, setOrderId] = useState('')
  const timerResult = useRef(null)
  const [isLoading, setIsLoading] = useState(false)
  const loadingTimer = useRef(null)
  const clearLoadingTimer = () => {
    if (loadingTimer.current) {
      clearTimeout(loadingTimer.current)
    }
  }
  const clearResultTimer = () => {
    if (timerResult.current) {
      clearInterval(timerResult.current)
    }
  }
  const close = () => {
    if (onClose) {
      onClose()
    } else {
      goBack()
    }
  }

  // 支付结果查询
  const getResult = async orderId => {
    const res = await getPayResult({
      orderId,
      sign: hashMD5(orderId)
    })
    //支付成功
    if (res.code === 0 && res.data.result === 'success') {
      clearOrderCache()
      clearResultTimer()
      h5PaySuccess?.()
      reportData(res.data, user)
      setTimeout(() => {
        window.location.reload()
      }, 20)
    }
  }

  useEffect(() => {
    clearLoadingTimer()
    clearResultTimer()
    if (payWay !== 1) {
      if (!localStorage.getItem('token')) {
        showLogin()
        return
      }
      setIsLoading(true)
      loadingTimer.current = setTimeout(() => {
        const pCode = vipData[selected].pCode
        const payFunc = payWay == 3 ? payCenter : payDirect
        payFunc({
          pCode,
          payWay,
          deviceType: 3,
          userId: user?.id
        }).then(res => {
          if (res.code === 0) {
            setIsLoading(false)
            setUrl(res.data.url)
            setOrderId(res.data.orderId)
          } else {
            message({ content: res.msg })
          }
        })
      }, 1000)
    }
  }, [payWay, selected])
  const toPay = async () => {
    if (!localStorage.getItem('token')) {
      showLogin()
      return
    }
    if (isLoading) {
      return
    }
    if (payWay !== 1) {
      openNewTab(url)
      clearResultTimer()
      timerResult.current = setInterval(() => {
        getResult(orderId)
      }, 6000)
    } else {
      setShowWechat(true)
    }
  }
  useEffect(() => {
    return () => {
      clearResultTimer()
    }
  }, [])
  return (
    <>
      <div className={cm(styles.vipH5, 'hideWhenPc')}>
        <div className={styles.title}>
          <img loading="lazy" src="/images/h-ar.png" alt="箭头" onClick={close} />
          <img loading="lazy" src={user?.token ? '/images/user.png' : '/images/defaultHead.png'} alt="用户头像" />
        </div>
        <img loading="lazy" src="/images/pay-h5-bg.webp" className={styles.vipBg} alt="支付背景" />
        <div style={{ marginTop: 64 }}>
          {vipData.map((item, index) => {
            const nol =  item.pCount > 7 ? (Math.floor(item.pCount / 30) + '个月') : item.pCount +'天'
            return (
              <div
                key={index}
                className={cm(styles.itemMeal, selected === index ? styles.active : styles.normal)}
                onClick={() => setSelected(index)}
              >
                {item.cornerMark ? <span className={styles.cornerMark}>{item.cornerMark}</span> : null}
                <div className={styles.info}>
                  <div className={styles.infoDate}>
                    <span className={styles.desc}>{item.pDesc || nol}</span>
                    {item.discountMark ? <p className={styles.discountMark}>{item.discountMark}</p> : null}
                  </div>
                  <div className={styles.price}>
                    {item.tagMark ? <p className={styles.popular}>{item.tagMark}</p> : null}
                    <span className={styles.span1}>$</span>
                    <span className={styles.span2}>{(item.usdPrice / 100).toFixed(1)}</span>
                  </div>
                </div>
              </div>
            )
          })}
        </div>
        <div className={styles.vipChoose}>
          <img loading="lazy" src="/images/vip.png" alt="vip" />
          <span>支付方式</span>
        </div>
        <div className={styles.vipPayWay}>
          {payArr.map((item, index) => {
            return (
              <div
                className={cm(styles.payWayItem, payWay === item.value ? styles.active : '')}
                key={index}
                onClick={() => setPayWay(item.value)}
              >
                <img loading="lazy" src={item.icon} alt={item.name} />
                <span>{item.name}</span>
              </div>
            )
          })}
        </div>
        <div className={styles.vipChoose}>
          <img loading="lazy" src="/images/vip.png" alt="vip" />
          <span>VIP权益</span>
        </div>
        <div className={styles.vipQuanxian}>
          {quanyiArr.map((item, index) => {
            return (
              <div key={index} className={styles.quanxianItem}>
                <div className={styles.iconBox}>
                  <img loading="lazy" src={item.icon} alt={item.title} />
                </div>
                <p className={styles.vtitle}>{item.title}</p>
              </div>
            )
          })}
        </div>
        <Button className={cm(styles.pay, isLoading ? 'opacity-80' : 'opacity-100')} onClick={toPay}>
          {isLoading ? <FetchLoading /> : null}
          开通VIP
        </Button>
      </div>
      {showWechat ? (
        <WechatPay getResult={getResult} pCode={vipData[selected].pCode} onClose={() => setShowWechat(false)} />
      ) : null}
    </>
  )
}

export default Index
